<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    protected $dontReport = [
        //
    ];

    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $e
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $e)
    {
        // API 请求统一异常处理
        // 检查是否是 API 请求：路径包含 /api/ 或者请求期望 JSON 响应
        if ($request->is('api/*') || 
            $request->expectsJson() || 
            $request->header('Accept') === 'application/json' ||
            $request->header('Content-Type') === 'application/json') {
            return $this->handleApiException($request, $e);
        }

        return parent::render($request, $e);
    }

    /**
     * 处理 API 异常
     *
     * @param Request $request
     * @param Throwable $e
     * @return \Illuminate\Http\JsonResponse
     */
    protected function handleApiException(Request $request, Throwable $e)
    {
        // 记录所有异常到日志
        try {
            \Log::error('API异常: ' . $e->getMessage(), [
                'exception' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString(),
                'request_url' => $request->fullUrl(),
                'request_method' => $request->method(),
                'request_data' => $request->all(),
            ]);
        } catch (\Exception $logException) {
            // 如果日志记录失败，忽略错误
        }

        // 验证异常
        if ($e instanceof ValidationException) {
            return response()->json([
                'code' => 422,
                'message' => '验证失败',
                'errors' => $e->errors(),
            ], 422)->header('Content-Type', 'application/json');
        }

        // 模型未找到异常
        if ($e instanceof ModelNotFoundException) {
            return response()->json([
                'code' => 404,
                'message' => '资源不存在',
            ], 404)->header('Content-Type', 'application/json');
        }

        // 路由未找到异常
        if ($e instanceof NotFoundHttpException) {
            return response()->json([
                'code' => 404,
                'message' => '接口不存在',
            ], 404)->header('Content-Type', 'application/json');
        }

        // 方法不允许异常
        if ($e instanceof MethodNotAllowedHttpException) {
            return response()->json([
                'code' => 405,
                'message' => '请求方法不允许',
            ], 405)->header('Content-Type', 'application/json');
        }

        // 其他异常
        $statusCode = method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500;
        $message = $e->getMessage() ?: '服务器错误';

        // 开发环境显示详细错误信息
        $isDevelopment = config('app.env') !== 'production' || config('app.debug');
        
        $responseData = [
            'code' => $statusCode,
            'message' => $isDevelopment ? $message : '服务器错误，请稍后重试',
        ];
        
        if ($isDevelopment) {
            $responseData['file'] = $e->getFile();
            $responseData['line'] = $e->getLine();
            $responseData['exception'] = get_class($e);
        }
        
        return response()->json($responseData, $statusCode)
            ->header('Content-Type', 'application/json')
            ->header('Accept', 'application/json');
    }
}

